from itsdangerous import TimedJSONWebSignatureSerializer as TJWSSerializer
from django.conf import settings
from itsdangerous import BadData

from . import constants

def generate_save_user_token(openid):
    """
    将明文openid序列化成密文openid
    :param openid: 明文openid
    :return: 密文openid
    """
    # 创建序列化器对象
    s = TJWSSerializer(settings.SECRET_KEY, expires_in=constants.SAVE_QQ_USER_TOKEN_EXPIRES)
    # 构造原始的数据
    data = {'openid': openid}
    # 序列化字典;dumps返回bytes类型的数据
    token = s.dumps(data).decode()

    return token

def check_save_user_token(access_token):
    """
    将密文openid转成明文openid
    :param access_token:密文openid
    :return:明文openid
    """
    # 创建序列化器对象
    s = TJWSSerializer(settings.SECRET_KEY, expires_in=constants.SAVE_QQ_USER_TOKEN_EXPIRES)
    # 解码密文openid
    try:
        data = s.loads(access_token)
        openid = data.get('openid')
    except BadData:
        return None
    else:
        return openid
